package com.joysuch.wwyt.edu.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.core.bean.BpUserListBean;
import com.joysuch.wwyt.core.bean.SimpleListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.ajax.ResultBeanPlus;
import com.joysuch.wwyt.core.entity.BaseManageType;
import com.joysuch.wwyt.core.entity.BaseTypeGroup;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.service.BaseManageTypeService;
import com.joysuch.wwyt.core.service.BaseTypeGroupItemService;
import com.joysuch.wwyt.core.service.BaseTypeGroupService;
import com.joysuch.wwyt.core.service.BaseUserService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.bean.EduCertificateNotifyPageVO;
import com.joysuch.wwyt.edu.entity.EduCertificateNotify;
import com.joysuch.wwyt.edu.entity.WwytEduCertificate;
import com.joysuch.wwyt.edu.schedule.EduCertificateNotifySchedule;
import com.joysuch.wwyt.edu.service.EduCertificateNotifyService;
import com.joysuch.wwyt.edu.service.WwytEduCertificateService;
import com.joysuch.wwyt.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 证书提醒Controller
 *
 * @author eric
 * @date 2021-04-16
 */

@RestController
@RequestMapping("/edu/certificate-notify")
@Api(tags = "/edu/certificate-notify 教育-证书提醒")
public class EduCertificateNotifyController {

    @Autowired
    private EduCertificateNotifyService eduCertificateNotifyService;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseManageTypeService baseManageTypeService;
    @Autowired
    private BaseTypeGroupItemService baseTypeGroupItemService;
    @Autowired
    private WwytEduCertificateService wwytEduCertificateService;


    /**
     * 查询证书提醒列表
     *
     * @return
     */
    @ApiOperation("查询证书提醒列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数", defaultValue = "1", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", required = false)
    })
    @GetMapping("/list")
    public ResultBeanPlus<EduCertificateNotifyPageVO> list(@RequestParam(required = false, defaultValue = "1") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<EduCertificateNotify> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(EduCertificateNotify::getUpdateTime);
        lqw.eq(EduCertificateNotify::getTenentId, Context.getCurrentTenantId());
        lqw.eq(EduCertificateNotify::getOrgCode, Context.getCompanyCode());
        IPage<EduCertificateNotify> page = eduCertificateNotifyService.page(new Page<>(pageNum + 1, pageSize), lqw);

        List<EduCertificateNotifyPageVO> pageVOList = Lists.newArrayList();
        List<EduCertificateNotify> pageRecords = page.getRecords();
        if (CollUtil.isNotEmpty(pageRecords)) {
            for (EduCertificateNotify record : pageRecords) {
                EduCertificateNotifyPageVO vo = new EduCertificateNotifyPageVO();
                BeanUtil.copyProperties(record, vo, "objId");
                vo.setAheadDaysDesc(vo.getAheadDays() + "天");
                String certificateIds = vo.getCertificates();
                if (StringUtil.notEmpty(certificateIds)) {
                    String[] ids = certificateIds.split(",");
                    List<Long> certIdList = new ArrayList<>();
                    for (String id : ids) {
                        certIdList.add(Long.valueOf(id));
                    }
                    Collection<WwytEduCertificate> wwytEduCertificates = wwytEduCertificateService.listByIds(certIdList);
                    if (CollectionUtils.isNotEmpty(wwytEduCertificates)) {
                        String collect = wwytEduCertificates.stream().map(WwytEduCertificate::getName).collect(Collectors.joining("、"));
                        vo.setCertificateNames(collect);
                    }
                }
                List<Long> ids = new ArrayList<>();
                if (StringUtils.isNotBlank(record.getObjId())) {
                    String[] split = record.getObjId().split(",");
                    for (String str : split) {
                        ids.add(Long.valueOf(str));
                    }
                }
                //人员用ObjectList  管理类型用ObjectId
                switch (vo.getObjType()) {
                    case 0:
                        vo.setObjTypeDesc("人员");
                        if (!CollectionUtils.isEmpty(ids)) {
                            List<SimpleListBean> objList = new ArrayList<>();
                            for (Long id : ids) {
                                SimpleListBean bean = new SimpleListBean();
                                BpUserListBean user = baseUserService.findById(id);
                                if (user != null) {
                                    bean.setName(user.getRealName());
                                    bean.setId(user.getId());
                                    objList.add(bean);
                                }
                            }
                            vo.setObjList(objList);
                        }
                        break;
                    case 1:
                        vo.setObjTypeDesc("部门负责人");
                        break;
                    case 2:
                        vo.setObjTypeDesc("管理类型");
                        if (!CollectionUtils.isEmpty(ids)) {
                            vo.setObjId(ids.get(0));
                            BaseTypeGroupItem manageType = baseTypeGroupItemService.findById(ids.get(0));
                            if (manageType != null) {
                                vo.setObjName(manageType.getName());
                            }
                        }
                        break;
                    default:
                        vo.setObjTypeDesc("未知");
                }
                switch (vo.getType()) {
                    case 0:
                        vo.setTypeDesc("有效期到期提醒");
                        break;
                    case 1:
                        vo.setTypeDesc("复证到期提醒");
                        break;
                    default:
                        vo.setTypeDesc("未知");
                }
                pageVOList.add(vo);
            }
        }

        return ResultBeanPlus.pageData(pageVOList, page.getTotal());
    }

    /**
     * 获取证书提醒详细信息
     */
    @ApiOperation("获取证书提醒详细信息")
    @GetMapping(value = "/info/{id}")
    public ResultBeanPlus<EduCertificateNotify> getInfo(@PathVariable("id") Long id) {
        EduCertificateNotify notify = eduCertificateNotifyService.getById(id);

        return ResultBeanPlus.success(eduCertificateNotifyService.getById(id));
    }

    /**
     * 新增证书提醒
     */
    @ApiOperation("保存证书提醒")
    @PostMapping(value = "/save")
    @RequiresPermissions("edu:certificate-notify:save")
    public ResultBean add(@RequestBody EduCertificateNotify eduCertificateNotify) {

        if (ObjectUtil.isNull(eduCertificateNotify.getId())) {
            eduCertificateNotify.setCreateBy(Context.getCurrentUserId());
            eduCertificateNotify.setCreateTime(new Date());
            eduCertificateNotify.setUpdateTime(new Date());
            eduCertificateNotify.setTenentId(Context.getCurrentTenantId());
            eduCertificateNotify.setOrgCode(Context.getCompanyCode());
        } else {
            eduCertificateNotify.setUpdateBy(Context.getCurrentUserId());
            eduCertificateNotify.setUpdateTime(new Date());
        }

        try {
            eduCertificateNotifyService.saveEduCertificateNotify(eduCertificateNotify);
            return ResultBean.defaultSuccessResult();
        } catch (RuntimeException e) {
            return ResultBean.fail(400, e.getMessage());
        }

    }

    /**
     * 删除证书提醒
     */
    @ApiOperation("删除证书提醒")
    @PostMapping(value = "/del")
    @RequiresPermissions("edu:certificate-notify:del")
    public ResultBean remove(@NotEmpty(message = "请勾选删除项") @RequestBody List<Long> idList) {

        eduCertificateNotifyService.removeByIds(idList);
        return ResultBean.defaultSuccessResult();
    }

    @Autowired
    private EduCertificateNotifySchedule eduCertificateNotifySchedule;

    @GetMapping(value = "/job")
    public ResultBean job() {
        eduCertificateNotifySchedule.checkExpired();
        return ResultBean.defaultSuccessResult();
    }
}
